package uploader

import (
    "fmt"
    "github.com/jlaffaye/ftp"
    "log"
    "strings"
    "time"
    "upload-ftp/config"
)

type Ftp struct {
    Client *ftp.ServerConn
}

func ConnectFtp() (*Ftp, error) {
    f := new(Ftp)
    dial := fmt.Sprintf("%s:%d", config.Ftp.Host, config.Ftp.Port)
    c, err := ftp.Dial(dial, ftp.DialWithTimeout(30*time.Second))
    if err != nil {
        return nil, err

    }
    err = c.Login(config.Ftp.Username, config.Ftp.Password)
    if err != nil {
        return nil, err
    }
    f.Client = c
    return f, nil
}

func (f *Ftp) reConnect() {
    for {
        time.Sleep(time.Second)
        fp, err := ConnectFtp()
        if err != nil || fp == nil {
            log.Println("ftp 重连失败，1秒后继续尝试连接。", err)
        } else {
            f.Client = fp.Client
            return
        }
    }
}

func (f *Ftp) MKDir(dir string) error {
    var err error
    if dir == "/" {
        return nil
    }
    dirs := strings.Split(dir, "/")
    tmpDir := ""
    for _, v := range dirs {
        if v == "" {
            continue
        }
        tmpDir = fmt.Sprintf("%s/%s", tmpDir, v)
        err = f.Client.ChangeDir(tmpDir)
        if err != nil {
            err = f.Client.MakeDir(tmpDir)
        }
    }
    f.Client.ChangeDir("/")
    return err
}

func (f *Ftp) Close() {
    f.Client.Quit()
}

func IsConnErr(err error) bool {
    index := strings.Index(err.Error(), "broken pipe")
    if index >= 0 {
        return true
    }
    index = strings.Index(err.Error(), "tcp")
    if index >= 0 {
        return true
    }
    index = strings.Index(err.Error(), "EOF")
    if index >= 0 {
        return true
    }
    return false
}
